package com.aerozhonghuan.logisticsmall.modules.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aerozhonghuan.foundation.base.BaseFragment;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.base.MatchPoneNumber;
import com.aerozhonghuan.logisticsmall.modules.common.MainActivity;
import com.aerozhonghuan.logisticsmall.modules.common.ServiceClauseActivity;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserBean;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserInfo;
import com.aerozhonghuan.logisticsmall.modules.user.logic.LoginLogic;
import com.aerozhonghuan.logisticsmall.modules.user.logic.UserInfoManager;
import com.aerozhonghuan.logisticsmall.utils.SafeHandler;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;

import org.json.JSONObject;

/**
 * 描述 手机号登录
 * 作者 zhangyonghui
 * 创建日期 2019-05-17
 */
public class LoginFragment extends BaseFragment {
    private static final String TAG = "LoginFragment";
    private static final String TYPE_SENDSMS_SMS = "1";
    private static final String TYPE_SENDSMS_CALL = "2";
    private Button btLogin;
    private TextView btYZM;
    private EditText etAccount;
    private EditText etPWD;
    private boolean isRecievingYZM = false;
    /**
     * 验证码倒计时
     */
    private int mTime = 90;
    private Handler mHander;
    private boolean isRecycle = false;
    private View rootView;
    private ProgressDialogIndicator dialog;
    private LinearLayout llLaw;
    private View.OnClickListener OnYZMClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String account = etAccount.getText().toString().trim();
            if (TextUtils.isEmpty(account)) {
                alert("请输入手机号");
                return;
            }
            if (!MatchPoneNumber.isPhoneNumber(account)) {
                alert("手机格式不正确");
                return;
            }
            sendMessageYZM(account);
        }
    };
    private View.OnClickListener OnLoginClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String account = etAccount.getText().toString();
            String pwd = etPWD.getText().toString();
            if (TextUtils.isEmpty(account)) {
                alert("请输入手机");
                return;
            }
            if (TextUtils.isEmpty(pwd)) {
                alert("请输入短信验证码");
                return;
            }
            if (!MatchPoneNumber.isPhoneNumber(account)) {
                alert("手机格式不正确");
                return;
            }
            login(account, pwd);
        }
    };
    private View.OnClickListener OnLawClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), ServiceClauseActivity.class);
            startActivity(intent);
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dialog = new ProgressDialogIndicator(getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.view_phonenum_login, null);
            mHander = new MyHandler(this);
            btLogin = (Button) rootView.findViewById(R.id.phone_bt_login);
            btLogin.setOnClickListener(OnLoginClick);
            btYZM = (TextView) rootView.findViewById(R.id.phone_tv_yzm);
            btYZM.setOnClickListener(OnYZMClick);
            etAccount = (EditText) rootView.findViewById(R.id.phone_et_account);
            etPWD = (EditText) rootView.findViewById(R.id.phone_et_pwd);
            llLaw = (LinearLayout) rootView.findViewById(R.id.phone_ll_law);
            llLaw.setOnClickListener(OnLawClick);
        }
        return rootView;
    }

    private void sendMessageYZM(String account) {
        if (!isRecievingYZM) {
            isRecycle = true;
            isRecievingYZM = true;
            sendMessage(account);
            btYZM.setTextColor(getResources().getColor(R.color.desc_text_color));
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    while (isRecycle) {
                        if (mTime > 0) {
                            Message msg = Message.obtain(mHander, 1);
                            msg.sendToTarget();
                            mTime = mTime - 1;
                        } else {
                            break;
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    mTime = 90;
                    Message msg = Message.obtain(mHander, 2);
                    msg.sendToTarget();
                }
            }.start();
        }
    }

    /**
     * 发送验证码
     * @param account
     */
    private void sendMessage(String account) {
        LoginLogic.sendSMS(getActivity(), account, TYPE_SENDSMS_SMS, dialog, new LoginLogic.OnSendSMSCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure() {
                mHander.sendEmptyMessage(2);
            }
        });
    }


    /**
     * 登录
     * @param account
     * @param pwd
     */
    private void login(final String account, final String pwd) {
        btLogin.setClickable(false);
        UserInfo userInfo = UserInfoManager.getCurrentUserBaseInfo();
        if (userInfo == null) {
            LoginLogic.checkToken(getActivity(), dialog, null, UserInfoManager.getDeviceId(), UserInfoManager.getUuid(), new LoginLogic.OnCheckTokenCallback() {
                @Override
                public void onSuccess(UserInfo userInfo) {
                    login(account, pwd);
                }

                @Override
                public void onFailure() {

                }
            });
        } else {
            LoginLogic.login(getActivity(), userInfo.getToken(), account, pwd, dialog, new LoginLogic.OnLoginCallback() {
                @Override
                public void onSuccess(UserBean userBean) {
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }

                @Override
                public void onFailure(String allResponseString) {
                    btLogin.setClickable(true);
                    isRecycle = false;
                    try {
                        if (!TextUtils.isEmpty(allResponseString)) {
                            JSONObject obj = new JSONObject(allResponseString);
                            String message = obj.getString("msg");
                            alert(message);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        alert("当前网络连接失败");
                    }
                }
            });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            dialog.release();
        }
    }

    private static class MyHandler extends SafeHandler<LoginFragment> {

        public MyHandler(LoginFragment var1) {
            super(var1);
        }

        @Override
        public void handleMessage(Message msg) {
            LoginFragment fragment = getInnerObject();
            if (fragment == null) {
                return;
            }

            int what = msg.what;
            if (what == 1) {
                fragment.btYZM.setText("重新获取(" + fragment.mTime + ")");
            } else if (what == 2) {
                fragment.isRecievingYZM = false;
                fragment.isRecycle = false;
                if (fragment != null && fragment.getActivity() != null) {
                    fragment.btYZM.setTextColor(fragment.getResources().getColor(R.color.colorPrimary));
                }
                fragment.btYZM.setText("重新获取");
            }

            super.handleMessage(msg);
        }
    }
}
